function jsRasterLine(start,end)
{
  this.start = start;
  this.end = end;
  
  this.delta = this.end.sub(this.start);
  this.size = this.delta.abs();
  this.min = this.start.min(this.end);
  this.max = this.start.max(this.end);
}

jsRasterLine.prototype.percentage = function (pos,min,size)
{
  return (pos - min) / size;
}

jsRasterLine.prototype.scale = function (percent,min,size)
{
  return (percent * size) + min;
}

jsRasterLine.prototype.getPointForX = function (x)
{
  var percent = this.percentage(x,this.start.x,this.delta.x);
  var y = this.scale(percent,this.start.y,this.delta.y);
  var z = this.scale(percent,this.start.z,this.delta.z);
  return $v(x,y,z);
}

jsRasterLine.prototype.getPointForY = function (y)
{
  var percent = this.percentage(y,this.start.y,this.delta.y);
  var x = this.scale(percent,this.start.x,this.delta.x);
  var z = this.scale(percent,this.start.z,this.delta.z);
  return $v(x,y,z);
}

jsRasterLine.prototype.getPointForZ = function (z)
{
  var percent = this.percentage(z,this.start.z,this.delta.z);
  var x = this.scale(percent,this.start.x,this.delta.x);
  var y = this.scale(percent,this.start.y,this.delta.y);
  return $v(x,y,z);
}




function jsRaster(name)
{
  jsViewport.call(this,name);
}

jsRaster.inherit(jsViewport);

jsRaster.prototype.drawLine = function (v1,v2,colour)
{
  var line = new jsRasterLine(v1,v2);
  
  if(line.size.x > line.size.y)
  {
    for(var x=line.min.x;x<line.max.x;x++)
    {
      var point = line.getPointForX(x);
      var positiveGap = Math.abs(parseInt(point.y) - point.y);
      var negativeGap = 1.0 - positiveGap;
      point.y = floor(point.y);
      this.drawPixel(point.x,point.y,point.z,colour.r,colour.g,colour.b,colour.a * negativeGap);
      
      if(positiveGap == 0)
        this.drawPixel(point.x,point.y + 1,point.z,colour.r,colour.g,colour.b,colour.a * positiveGap);
    }
  } else {
    for(var y=line.min.y;y<line.max.y;y++)
    {
      var point = line.getPointForY(y);
      var positiveGap = Math.abs(parseInt(point.x) - point.x);
      var negativeGap = 1.0 - positiveGap;
      point.x = floor(point.x);
      this.drawPixel(point.x,point.y,point.z,colour.r,colour.g,colour.b,colour.a * negativeGap);
      
      if(positiveGap == 0)
        this.drawPixel(point.x + 1,point.y,point.z,colour.r,colour.g,colour.b,colour.a * positiveGap);
    }    
  }
}


function main()
{
  var r = new jsRaster('fg');
  r.drawLine($p(0,0,0),$p(640,480,0),$c(255,0,0));
  r.drawLine($p(0,480,0),$p(640,0,0),$c(255,0,0));
  r.drawLine($p(320,0,0),$p(320,480,0),$c(255,0,0));
  r.drawLine($p(0,240,0),$p(640,240,0),$c(255,0,0));
  r.swapBuffer();
  
  return;
}
